package com.xiao.dynamic_rule.service;

import com.xiao.dynamic_rule.pojo.LogBean;
import com.xiao.dynamic_rule.pojo.RuleParam;
import com.xiao.dynamic_rule.pojo.RuleParamAtomic;
import com.xiao.dynamic_rule.utils.RuleCalcUtil;
import org.apache.flink.api.common.state.ListState;

import java.util.List;

/**
 * 用户行为次数类条件查询服务实现，在flink的state中查询
 */
public class UserActionCountQueryServiceStateImpl implements UserActionCountQueryService {

    ListState<LogBean> eventState;
    public UserActionCountQueryServiceStateImpl(ListState<LogBean> eventState){

        this.eventState = eventState;
    }

    public UserActionCountQueryServiceStateImpl(){}
    /**
     * 查询规则参数中，要求的用户行为的次数类条件是否满足，同时将查到的满足条件的次数 set回 传入的规则参数中
     *
     * @param eventState 用户事件明细存储state
     * @param ruleParam  规则整体参数对象
     * @return 此用户是否符合该规则条件
     */
    @Override
    public boolean queryActionCounts(String deviceId,ListState<LogBean> eventState, RuleParam ruleParam) throws Exception {

        //从传入的条件对象中取出用户的行为条件
        List<RuleParamAtomic> userActionCountParams = ruleParam.getUserActionCountParams();
        //从flink state中取出用户历史数据
        Iterable<LogBean> logBeans = eventState.get();

        //得到是否符合条件，并且得到行为次数
        queryActionCountHelper(logBeans,userActionCountParams);

        // 判断真实做过的行为次数是否满足条件中的行为次数,若有一个不满足则直接返回 false
        for (RuleParamAtomic userActionCountParam : userActionCountParams) {
            if (userActionCountParam.getCnts() > userActionCountParam.getRealCunts()){
                return false;
            }
        }
        //如果都满足则返回true
        return true;
    }


    /**
     * 将用户的历史数据中的行为判断是否符合传入的条件，然后将用户做过的行为的次数 set 回规则对象中，方便判断和后面使用
     * @param logBeans
     * @param userActionCountParams
     */
    public void queryActionCountHelper(Iterable<LogBean> logBeans, List<RuleParamAtomic> userActionCountParams) {

        for (LogBean logBean : logBeans) {
            for (RuleParamAtomic userActionCountParam : userActionCountParams) {

                //判断当前logbean和当前规则原子 条件userActionCountParam 是否一致
                boolean isMatch = RuleCalcUtil.eventBeanMatchEventParam(logBean, userActionCountParam,true);

                //增加时间约束
                if (isMatch){
                    //如果一致，加一,并且将次数 set 回规则对象中
                    userActionCountParam.setRealCunts(userActionCountParam.getRealCunts() + 1);
                    //如果不一致则下一次循环
                }
            }
        }
    }

    /**
     * 查询单个count条件是否满足
     */
    @Override
    public boolean queryActionCount(String deviceId, ListState<LogBean> eventState, RuleParamAtomic atomicParam) throws Exception {
        return false;
    }
}
